package com.cloud.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;


@Slf4j
public class ApiSign {



	private static final String SIGNKEY="4aadeef29ad04057ba3933a4075e563a";


	/**
	 * 获取签名算法
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String getSignature(Map<String,String> params){
		String stringMd5 ="";
		try {
			// 先将参数以其参数名的字典序升序进行排序
			Map<String, String> sortedParams = new TreeMap<String, String>(params);
			Set<Entry<String, String>> entrys = sortedParams.entrySet();

			// 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
			StringBuilder basestring = new StringBuilder();
			for (Entry<String, String> param : entrys) {
				String paramV = URLEncoder.encode(param.getValue(), "UTF-8");
				String value = URLDecoder.decode(paramV, "UTF-8");
//	    	if("iOS".equals(channelType)){
//	    		value=value.replaceAll("\\+", "%20");
//	    	}
				basestring.append(param.getKey()).append("=").append(value).append("&");
			}
			basestring.append("signKey="+ApiSign.SIGNKEY);
			//将请求参数安装英文字母升序拼接后md5得到字符串
			stringMd5 = Md5Utils.MD5(basestring.toString());
		}catch (Exception e){
			log.error("签名错误",e);
		}
		return stringMd5;
	}

}
